package com.roger.ndtplayer.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Process
import android.provider.Settings
import android.text.InputFilter
import android.text.TextUtils
import android.widget.EditText
import android.widget.Toast
import com.roger.ndtplayer.App
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern


/**
 * Creator Email：xuqiankun@smzdm.com
 * Description：
 */

// 当前网络是否可用
fun isNetAvailable(): Boolean {
    val connectivityManager =
        App.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    @Suppress("DEPRECATION")
    val netInfo = connectivityManager.activeNetworkInfo
    @Suppress("DEPRECATION")
    return netInfo?.isConnected == true
//    }
}

private val toastInstance: Toast by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
    Toast.makeText(App.instance, "", Toast.LENGTH_SHORT)
}

fun showToast(s: String?) {
    if (s.isNullOrEmpty()) return

    Handler(App.instance.mainLooper).post {
        toastInstance.run {
            duration = Toast.LENGTH_SHORT
            setText(s)
//            setGravity(Gravity.BOTTOM, 0, 0)
            try {
                show()
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            }
        }
    }
}

fun showToast(sRes: Int?) {
    if (sRes != null && sRes > 0)
        showToast(App.instance.resources.getString(sRes))
}

fun showLongToast(s: String?) {
    if (s.isNullOrEmpty()) return

    Handler(App.instance.mainLooper).post {
        toastInstance.run {
            duration = Toast.LENGTH_LONG
            setText(s)
//            setGravity(Gravity.BOTTOM, 0, 0)
            try {
                show()
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            }
        }
    }
}

fun showLongToast(sRes: Int?) {
    if (sRes != null && sRes > 0)
        showLongToast(App.instance.resources.getString(sRes))
}


fun getSystemProperties(propName: String): String {
    var line: String = ""
    var inputReader: BufferedReader? = null

    try {
        val p = Runtime.getRuntime().exec("getprop $propName")
        inputReader = BufferedReader(InputStreamReader(p.inputStream), 1024)
        line = inputReader.readLine()
        inputReader.close()
    } catch (e: IOException) {
        return ""
    } finally {
        if (line.isNotEmpty()) {
            inputReader?.close()
        }
    }
    return line
}

fun getScreenWidth() = App.instance.resources.displayMetrics.widthPixels

fun getScreenHeight() = App.instance.resources.displayMetrics.heightPixels

/**
 * 长宽比超过2，就认为是长屏手机
 */
fun isLongScreen() = getScreenHeight().toFloat() / getScreenWidth() > 2

/**
 * 获取状态栏高度
 */
fun getStatusBarHeight(): Int {
    val resourceId = App.instance.resources.getIdentifier("status_bar_height", "dimen", "android")
    return if (resourceId > 0) {
        App.instance.resources.getDimensionPixelOffset(resourceId)
    } else 0
}

/**
 * 获取导航栏高度
 */
fun getBottomNavHeight(): Int {
    if (hasBottomNav()) {
        val resourceId =
            App.instance.resources.getIdentifier("navigation_bar_height", "dimen", "android")

        return if (resourceId > 0) {
            App.instance.resources.getDimensionPixelOffset(resourceId)
        } else 0
    } else {
        return 0
    }
}

/**
 * 是否有底部导航栏
 */
@SuppressLint("PrivateApi")
fun hasBottomNav(): Boolean {
    var hasNavBar: Boolean = false
    val id = App.instance.resources.getIdentifier("config_showNavigationBar", "bool", "android")
    if (id > 0) {
        hasNavBar = App.instance.resources.getBoolean(id)
    }
    try {
        val sysPropClass = Class.forName("android.os.SystemProperties")
        val m = sysPropClass.getMethod("get", String::class.java)
        val navBarOverride = m.invoke(sysPropClass, "qemu.hw.mainkeys")
        if (navBarOverride == "1") {
            hasNavBar = false
        } else if (navBarOverride == "0") {
            hasNavBar = true
        }
    } catch (e: Exception) {
    }
    return hasNavBar
}

//是否是个手机号
fun isValidPhone(s: String?): Boolean {
    if (s == null) return false
    val p = s.replace(" ", "")
    return p.length == 11 && p.startsWith("1")
}

/**
 * 获取进程号对应的进程名
 *
 * @param pid 进程号
 * @return 进程名
 */
fun getProcessName(pid: Int): String? {
    var reader: BufferedReader? = null
    try {
        reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
        var processName = reader.readLine()
        if (!TextUtils.isEmpty(processName)) {
            processName = processName.trim { it <= ' ' }
        }
        return processName
    } catch (throwable: Throwable) {
        throwable.printStackTrace()
    } finally {
        try {
            reader?.close()
        } catch (exception: IOException) {
            exception.printStackTrace()
        }

    }
    return null
}

/**
 * 获取主进程的名称
 *
 * @param context Context
 * @return 主进程名称
 */
fun getMainProcessName(context: Context?): String? {
    context ?: return ""

    return try {
        context.applicationContext.applicationInfo.processName
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

/**
 * 判断当前进程名称是否为主进程
 *
 * @param context Context
 * @return 是否主进程
 */
fun isMainProcess(context: Context?): Boolean {
    context ?: return false
    val mainProcessName = getMainProcessName(context)
    if (mainProcessName.isNullOrEmpty()) return true

    val currentProcess = getCurrentProcessName(context.applicationContext)
    return currentProcess.isNullOrEmpty() || mainProcessName == currentProcess
}

/**
 * 获得当前进程的名字
 *
 * @param context Context
 * @return 进程名称
 */
fun getCurrentProcessName(context: Context): String? {
    try {
        val pid = Process.myPid()
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
            ?: return null
        val runningAppProcessInfoList = activityManager.runningAppProcesses
        if (runningAppProcessInfoList != null) {
            for (appProcess in runningAppProcessInfoList) {
                if (appProcess != null) {
                    if (appProcess.pid == pid) {
                        return appProcess.processName
                    }
                }
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

/**
 * 打开权限设置页面
 */
fun openPermissionSetting(activity: Activity) {
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
        openSystemConfig(activity)
    } else {
        try {
            openApplicationInfo(activity)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            openSystemConfig(activity)
        }
    }
}

/**
 * 打开应用信息界面
 */
fun openApplicationInfo(activity: Activity) {
    val localIntent = Intent()
    localIntent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    localIntent.data = Uri.fromParts("package", App.instance.packageName, null)
    activity.startActivity(localIntent)
}

/**
 * 打开系统设置页面
 */
fun openSystemConfig(activity: Activity) {
    try {
        val intent = Intent(Settings.ACTION_SETTINGS)
        activity.startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

/**
 * 判断email格式是否正确
 */
fun isEmail(email: String?): Boolean {
    val str =
        "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"
    val p: Pattern = Pattern.compile(str)
    val m: Matcher = p.matcher(email)
    return m.matches()
}


/**
 * 针对EditText，限制其输入长度，对输入文本进行过滤
 */
fun editTextLimit(editText: EditText, number: Int) {
    val filter =
        InputFilter { source, start, end, dest, dstart, dend ->
            if (source == "·" || source == "*") {
                return@InputFilter null
            }
            for (i in start until end) {
                if (!Character.isLetterOrDigit(source[i])
                    && source[i].toString() != "_"
                    && source[i].toString() != "-"
                ) {
                    return@InputFilter ""
                }
            }
            if (source == " " || source.toString().contentEquals("\n")) {
                ""
            } else {
                null
            }
        }
    editText.filters = arrayOf(filter, InputFilter.LengthFilter(number))
}

fun getNowTime(): String {
    //获取当前时间
    val date = Date()
    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

    return dateFormat.format(date)
}



